var mysql = require('mysql2');
const constant = require('../private/constant');


class MySQL{

    constructor(){
        this.pool = mysql.createPool({
            host: constant.DBHost,
            user: constant.DBUser,
            password: constant.DBKey,
            database: constant.DBdatabase
        })

        this.promisePool = this.pool.promise()
    }
    
    query = async (sql, options) => {
        return await this.promisePool.query(sql, options)
    }

    queryCallback = async (sql, options, res, callback,
                           onlyFirst=false, noResultError=true
    ) =>{
        try {
            let [result, fields] = await this.promisePool.query(sql, options)
            if (noResultError && result.length === 0){
                throw Error('SQL_NO_RESULT')
            }
            callback(onlyFirst? result[0] : result)
        }catch (e){
            console.log('error', e, sql, options)
            res.json({
                success: false,
                errorInfo: e.message,
                errorVerbose: e
            })
        }
    }

    queryRespond = async (sql, options, res,
        onlyFirst=false, noResultError=true
    ) => {
        try {
            let [result, fields] = await this.promisePool.query(sql, options)
            if (noResultError && result.length === 0){
                throw Error('SQL_NO_RESULT')
            }
            res.json({
                success: true,
                data:{
                    body: onlyFirst? result[0] : result,
                    len: result.length
                }
            })
        }catch (e){
            console.log('error', e, sql, options)
            res.json({
                success: false,
                errorInfo: e.message === 'SQL_NO_RESULT'? e.message : 'SQL_QUERY_ERROR',
                errorVerbose: e
            })
        }
    }


}

db = new MySQL()

module.exports = db


